﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//导入命名空间
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;

namespace stwh_Common
{
    /// <summary>
    /// 图片处理类
    /// </summary>
    public class ImageHepler
    {
        public ImageHepler()
        { }

        /// <summary>  
        /// 用灰度数组新建一个8位灰度图像。  
        /// </summary>  
        /// <param name="rawValues"> 灰度数组(length = width * height)。 </param>  
        /// <param name="width"> 图像宽度。 </param>  
        /// <param name="height"> 图像高度。 </param>  
        /// <returns> 新建的8位灰度位图。 </returns>  
        public static Bitmap BuiltGrayBitmap(byte[] rawValues, int width, int height)
        {
            // 新建一个8位灰度位图，并锁定内存区域操作  
            Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
            BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);

            // 计算图像参数  
            int offset = bmpData.Stride - bmpData.Width;        // 计算每行未用空间字节数  
            IntPtr ptr = bmpData.Scan0;                         // 获取首地址  
            int scanBytes = bmpData.Stride * bmpData.Height;    // 图像字节数 = 扫描字节数 * 高度  
            byte[] grayValues = new byte[scanBytes];            // 为图像数据分配内存  

            // 为图像数据赋值  
            int posSrc = 0, posScan = 0;                        // rawValues和grayValues的索引  
            for (int i = 0; i < height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    grayValues[posScan++] = rawValues[posSrc++];
                }
                // 跳过图像数据每行未用空间的字节，length = stride - width * bytePerPixel  
                posScan += offset;
            }

            // 内存解锁  
            Marshal.Copy(grayValues, 0, ptr, scanBytes);
            bitmap.UnlockBits(bmpData);  // 解锁内存区域  

            // 修改生成位图的索引表，从伪彩修改为灰度  
            ColorPalette palette;
            // 获取一个Format8bppIndexed格式图像的Palette对象  
            using (Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
            {
                palette = bmp.Palette;
            }
            for (int i = 0; i < 256; i++)
            {
                palette.Entries[i] = Color.FromArgb(i, i, i);
            }
            // 修改生成位图的索引表  
            bitmap.Palette = palette;

            return bitmap;
        }

        /// <summary>  
        /// 将源图像灰度化，并转化为8位灰度图像。  
        /// </summary>  
        /// <param name="original"> 源图像。 </param>  
        /// <returns> 8位灰度图像。 </returns>  
        public static Bitmap RgbToGrayScale(Bitmap original)
        {
            if (original != null)
            {
                // 将源图像内存区域锁定  
                Rectangle rect = new Rectangle(0, 0, original.Width, original.Height);
                BitmapData bmpData = original.LockBits(rect, ImageLockMode.ReadOnly, original.PixelFormat);

                // 获取图像参数  
                int width = bmpData.Width;
                int height = bmpData.Height;
                int stride = bmpData.Stride;  // 扫描线的宽度  
                int offset = stride - width * 3;  // 显示宽度与扫描线宽度的间隙  
                IntPtr ptr = bmpData.Scan0;   // 获取bmpData的内存起始位置  
                int scanBytes = stride * height;  // 用stride宽度，表示这是内存区域的大小  
                // 分别设置两个位置指针，指向源数组和目标数组  
                int posScan = 0, posDst = 0;
                byte[] rgbValues = new byte[scanBytes];  // 为目标数组分配内存  
                Marshal.Copy(ptr, rgbValues, 0, scanBytes);  // 将图像数据拷贝到rgbValues中  
                // 分配灰度数组  
                byte[] grayValues = new byte[width * height]; // 不含未用空间。  
                // 计算灰度数组  
                for (int i = 0; i < height; i++)
                {
                    for (int j = 0; j < width; j++)
                    {
                        double temp = rgbValues[posScan++] * 0.114 + rgbValues[posScan++] * 0.587 + rgbValues[posScan++] * 0.299;
                        grayValues[posDst++] = (byte)temp;
                    }
                    // 跳过图像数据每行未用空间的字节，length = stride - width * bytePerPixel  
                    posScan += offset;
                }

                // 内存解锁  
                Marshal.Copy(rgbValues, 0, ptr, scanBytes);
                original.UnlockBits(bmpData);  // 解锁内存区域  

                // 构建8位灰度位图  
                Bitmap retBitmap = BuiltGrayBitmap(grayValues, width, height);
                return retBitmap;
            }
            else return null;
        }

        /// <summary>
        /// 图像灰度反转
        /// </summary>
        /// <param name="original">源图像</param>
        /// <returns></returns>
        public static Bitmap GrayScaleToRgb(Bitmap original)
        {
            Bitmap bmp = new Bitmap(original);
            for (int i = 0; i < bmp.Width; i++)
            {
                for (int j = 0; j < bmp.Height; j++)
                {
                    //获取该点的像素的RGB的颜色
                    Color color = bmp.GetPixel(i, j);
                    Color newColor = Color.FromArgb(255 - color.R, 255 - color.G, 255 - color.B);
                    bmp.SetPixel(i, j, newColor);
                }
            }
            return bmp;
        }

        /// <summary>
        /// 图像二值化1：取图片的平均灰度作为阈值，低于该值的全都为0，高于该值的全都为255
        /// </summary>
        /// <param name="original"></param>
        /// <returns></returns>
        public static Bitmap ConvertTo1Bpp1(Bitmap original)
        {
            Bitmap bmp = new Bitmap(original);
            int average = 0;
            for (int i = 0; i < bmp.Width; i++)
            {
                for (int j = 0; j < bmp.Height; j++)
                {
                    Color color = bmp.GetPixel(i, j);
                    average += color.B;
                }
            }
            average = (int)average / (bmp.Width * bmp.Height);
            for (int i = 0; i < bmp.Width; i++)
            {
                for (int j = 0; j < bmp.Height; j++)
                {
                    //获取该点的像素的RGB的颜色
                    Color color = bmp.GetPixel(i, j);
                    int value = 255 - color.B;
                    Color newColor = value > average ? Color.FromArgb(0, 0, 0) : Color.FromArgb(255,255, 255);
                    bmp.SetPixel(i, j, newColor);
                }
            }
            return bmp;
        }

        /// <summary>
        /// 图像二值化2
        /// </summary>
        /// <param name="original"></param>
        /// <returns></returns>
        public static Bitmap ConvertTo1Bpp2(Bitmap original)
        {
            Bitmap img = new Bitmap(original);
            int w = img.Width;
            int h = img.Height;
            Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
            BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite,

PixelFormat.Format1bppIndexed);
            for (int y = 0; y < h; y++)
            {
                byte[] scan = new byte[(w + 7) / 8];
                for (int x = 0; x < w; x++)
                {
                    Color c = img.GetPixel(x, y);
                    if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));
                }
                Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length);
            }
            return bmp;
        }

        /// <summary>
        /// 将字符串绘制到图片Bitmap对象上
        /// </summary>
        /// <param name="w">宽度</param>
        /// <param name="h">高度</param>
        /// <param name="srs">字符串</param>
        /// <returns></returns>
        public static Bitmap srBitmap(int w, int h, string srs)
        {
            //定义图片弯曲的角度
            int srseedangle = 45;
            //定义图象
            Bitmap srBmp = new Bitmap(w, h);
            //画图
            Graphics srGraph = Graphics.FromImage(srBmp);
            //清空图象
            srGraph.Clear(Color.AliceBlue);
            ////给图象画边框
            //srGraph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, srBmp.Width - 1, srBmp.Height - 1);
            //定义随即数
            Random srRandom = new Random();
            //定义画笔
            Pen srPen = new Pen(Color.LightGray, 0);
            //画噪点
            for (int i = 0; i < 100; i++)
            {
                srGraph.DrawRectangle(srPen, srRandom.Next(1, srBmp.Width - 2), srRandom.Next(1, srBmp.Height - 2), 1, 1);
            }
            //将字符串转化为字符数组
            char[] srchars = srs.ToCharArray();
            //封状文本
            StringFormat srFormat = new StringFormat(StringFormatFlags.NoClip);
            //设置文本垂直居中
            srFormat.Alignment = StringAlignment.Center;
            //设置文本水平居中
            srFormat.LineAlignment = StringAlignment.Center;
            //定义字体颜色
            Color[] srColors = { Color.Black, Color.Red, Color.DarkBlue, Color.Blue, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
            //定义字体
            string[] srFonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体", "微软雅黑" };
            //循环画出每个字符
            for (int i = 0, j = srchars.Length; i < j; i++)
            {
                //定义字体 参数分别为字体样式 字体大小 字体字形
                Font srFont = new Font(srFonts[srRandom.Next(5)], srRandom.Next(12, 20), FontStyle.Regular);
                //填充图形
                Brush srBrush = new SolidBrush(srColors[srRandom.Next(7)]);
                //定义坐标
                Point srPoint = new Point(16, 16);
                //定义倾斜角度
                float srangle = srRandom.Next(-srseedangle, srseedangle);
                //倾斜
                srGraph.TranslateTransform(srPoint.X, srPoint.Y);
                srGraph.RotateTransform(srangle);
                //填充字符
                srGraph.DrawString(srchars[i].ToString(), srFont, srBrush, 10, 3, srFormat);
                //回归正常
                srGraph.RotateTransform(-srangle);
                srGraph.TranslateTransform(2, -srPoint.Y);
            }
            srGraph.Dispose();
            return srBmp;
        }

        /// <summary>
        /// 随机获取颜色
        /// </summary>
        /// <returns></returns>
        public static Color getColor()
        {
            Random random = new Random();
            int red = 0, green = 0, blue = 0;
            // 产生随机的颜色分量来构造颜色值，这样输出的每位数字的颜色值都将不同。   
            red = random.Next(255);
            green = random.Next(255);
            blue = random.Next(255);
            return Color.FromArgb(red, green, blue);
        }

        /// <summary>
        /// 功能生成小图,+版权信息(文字)
        /// </summary>
        /// <param name="path">要保存的实际路径(文件夹名称)</param>
        /// <param name="file">aspx页面中的上传控件</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <param name="mode">裁剪方式</param>
        /// <param name="strInfo">版权信息</param>
        /// <param name="left">左边位置</param>
        /// <param name="top">上边位置</param>
        /// <returns>返回经过处理后的文件名（注意：除png格式外，其他均为jpg）</returns>
        public static string GetSamilImageAddCopyrightByStr(string path, FileUpload file, int width, int height, string mode, string strInfo, int left, int top)
        {
            path = HttpContext.Current.Server.MapPath("") + @"\" + path + @"\";
            string FileName = filename(file);
            if (File.Exists(FileName) == false)
            {
                file.PostedFile.SaveAs(path + FileName);//保存原图
                System.Drawing.Image oldimage = System.Drawing.Image.FromFile(path + FileName);
                int towidth = width;
                int toheight = height;
                int x = 0;
                int y = 0;
                int ow = oldimage.Width;
                int oh = oldimage.Height;
                switch (mode)
                {
                    case "hw"://指定高宽缩放（可能变形）                
                        break;
                    case "w"://指定宽，高按比例                    
                        toheight = oldimage.Height * width / oldimage.Width;
                        break;
                    case "h"://指定高，宽按比例
                        towidth = oldimage.Width * height / oldimage.Height;
                        break;
                    case "cut"://指定高宽裁减（不变形）                
                        if ((double)oldimage.Width / (double)oldimage.Height > (double)towidth / (double)toheight)
                        {
                            oh = oldimage.Height;
                            ow = oldimage.Height * towidth / toheight;
                            y = 0;
                            x = (oldimage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = oldimage.Width;
                            oh = oldimage.Width * height / towidth;
                            x = 0;
                            y = (oldimage.Height - oh) / 2;
                        }
                        break;
                    default:
                        break;
                }
                //新建一个bmp图片，并制定宽高
                System.Drawing.Image thumbnailImage = new Bitmap(towidth, toheight);
                //新建一个画板
                Graphics newpic = Graphics.FromImage(thumbnailImage);
                //设置高质量插值法
                newpic.InterpolationMode = InterpolationMode.High;
                //设置高质量,低速度呈现平滑程度
                newpic.SmoothingMode = SmoothingMode.HighQuality;
                //清空画布并以透明背景色填充
                newpic.Clear(Color.Transparent);
                //在指定位置并且按指定大小绘制原图片的指定部分
                newpic.DrawImage(oldimage, new Rectangle(0, 0, towidth, toheight),
                   new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);

                Bitmap output = new Bitmap(thumbnailImage);
                //添加版权
                Graphics g = Graphics.FromImage(output);
                //写入字符串
                g.DrawString(strInfo, new Font("Courier New", 14), new SolidBrush(Color.Red), left, top);
                string S_FileName = "s_" + FileName;
                switch (file.PostedFile.FileName.Split(".".ToCharArray())[1].ToUpper())
                {
                    case "JPEG":
                    case "JPG":
                        output.Save(path + S_FileName, ImageFormat.Jpeg);
                        break;
                    case "GIF":
                        output.Save(path + S_FileName, ImageFormat.Jpeg);
                        break;
                    case "PNG":
                        output.Save(path + S_FileName, ImageFormat.Png);
                        break;
                    case "BMP":
                        output.Save(path + S_FileName, ImageFormat.Jpeg);
                        break;
                    default:
                        output.Save(path + S_FileName, ImageFormat.Jpeg);
                        break;
                }
                output.Dispose();
                g.Dispose();
                oldimage.Dispose();
                return S_FileName;//返回处理后的图片名称
            }
            else//如果图片已经存在则返回0，虽然概率几乎是0，但我感觉还是加上比较稳妥，^_^
            {
                return "0";
            }
        }

        /// <summary>
        /// 功能生成小图,+版权信息(图片水印)
        /// </summary>
        /// <param name="path">要保存的实际路径(文件夹名称)/param>
        /// <param name="file">aspx页面中的上传控件</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <param name="mode">裁剪方式</param>
        /// <param name="strInfo">版权信息</param>
        /// <param name="left">左边位置</param>
        /// <param name="top">上边位置</param>
        /// <returns>返回经过处理后的文件名（注意：除png格式外，其他均为jpg）</returns>
        public static string GetSamilImageAddCopyrightByImg(string path, FileUpload file, int width, int height, string mode, string Path_sypf)
        {
            string FileName = filename(file);
            path = HttpContext.Current.Server.MapPath("") + @"\" + path + @"\";
            Path_sypf = HttpContext.Current.Server.MapPath("") + @"\" + Path_sypf;
            if (File.Exists(FileName) == false)
            {
                file.PostedFile.SaveAs(path + FileName);//保存原图
                System.Drawing.Image oldimage = System.Drawing.Image.FromFile(path + FileName);
                int towidth = width;
                int toheight = height;
                int x = 0;
                int y = 0;
                int ow = oldimage.Width;
                int oh = oldimage.Height;
                switch (mode)
                {
                    case "hw"://指定高宽缩放（可能变形）                
                        break;
                    case "w"://指定宽，高按比例                    
                        toheight = oldimage.Height * width / oldimage.Width;
                        break;
                    case "h"://指定高，宽按比例
                        towidth = oldimage.Width * height / oldimage.Height;
                        break;
                    case "cut"://指定高宽裁减（不变形）                
                        if ((double)oldimage.Width / (double)oldimage.Height > (double)towidth / (double)toheight)
                        {
                            oh = oldimage.Height;
                            ow = oldimage.Height * towidth / toheight;
                            y = 0;
                            x = (oldimage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = oldimage.Width;
                            oh = oldimage.Width * height / towidth;
                            x = 0;
                            y = (oldimage.Height - oh) / 2;
                        }
                        break;
                    default:
                        break;
                }
                //新建一个bmp图片，并制定宽高
                System.Drawing.Image thumbnailImage = new Bitmap(towidth, toheight);
                //新建一个画板
                Graphics newpic = Graphics.FromImage(thumbnailImage);
                //设置高质量插值法
                newpic.InterpolationMode = InterpolationMode.High;
                //设置高质量,低速度呈现平滑程度
                newpic.SmoothingMode = SmoothingMode.HighQuality;
                //清空画布并以透明背景色填充
                newpic.Clear(Color.Transparent);
                //在指定位置并且按指定大小绘制原图片的指定部分
                newpic.DrawImage(oldimage, new Rectangle(0, 0, towidth, toheight),
                   new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);

                System.Drawing.Image copyImage = System.Drawing.Image.FromFile(Path_sypf);
                Graphics g = Graphics.FromImage(thumbnailImage);
                g.DrawImage(copyImage, new Rectangle(thumbnailImage.Width - copyImage.Width,
                    thumbnailImage.Height - copyImage.Height, copyImage.Width, copyImage.Height),
                    0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);

                string S_FileName = "s_" + FileName;
                switch (file.PostedFile.FileName.Split(".".ToCharArray())[1].ToUpper())
                {
                    case "JPEG":
                    case "JPG":
                        thumbnailImage.Save(path + S_FileName, ImageFormat.Jpeg);
                        break;
                    case "GIF":
                        thumbnailImage.Save(path + S_FileName, ImageFormat.Jpeg);
                        break;
                    case "PNG":
                        thumbnailImage.Save(path + S_FileName, ImageFormat.Png);
                        break;
                    case "BMP":
                        thumbnailImage.Save(path + S_FileName, ImageFormat.Jpeg);
                        break;
                    default:
                        thumbnailImage.Save(path + S_FileName, ImageFormat.Jpeg);
                        break;
                }
                copyImage.Dispose();
                g.Dispose();
                oldimage.Dispose();
                return S_FileName;//返回处理后的图片名称
            }
            else//如果图片已经存在则返回0，虽然概率几乎是0，但我感觉还是加上比较稳妥，^_^
            {
                return "0";
            }
        }

        /// <summary>
        /// 指定宽、高按规定裁剪
        /// </summary>
        /// <param name="path">要保存的实际路径(文件夹名称)</param>
        /// <param name="file">aspx页面中的上传控件</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <param name="mode">裁剪方式</param>
        /// <returns>返回经过处理后的文件名（注意：除png格式外，其他均为jpg）</returns>
        public static string GetSamilImage(string path, FileUpload file, int width, int height, string mode)
        {
            string FileName = filename(file);
            path = HttpContext.Current.Server.MapPath("") + @"\" + path + @"\";
            if (File.Exists(FileName) == false)
            {
                file.PostedFile.SaveAs(path + FileName);//保存原图
                System.Drawing.Image oldimage = System.Drawing.Image.FromFile(path + FileName);
                int towidth = width;
                int toheight = height;
                int x = 0;
                int y = 0;
                int ow = oldimage.Width;
                int oh = oldimage.Height;
                switch (mode)
                {
                    case "hw"://指定高宽缩放（可能变形）                
                        break;
                    case "w"://指定宽，高按比例                    
                        toheight = oldimage.Height * width / oldimage.Width;
                        break;
                    case "h"://指定高，宽按比例
                        towidth = oldimage.Width * height / oldimage.Height;
                        break;
                    case "cut"://指定高宽裁减（不变形）                
                        if ((double)oldimage.Width / (double)oldimage.Height > (double)towidth / (double)toheight)
                        {
                            oh = oldimage.Height;
                            ow = oldimage.Height * towidth / toheight;
                            y = 0;
                            x = (oldimage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = oldimage.Width;
                            oh = oldimage.Width * height / towidth;
                            x = 0;
                            y = (oldimage.Height - oh) / 2;
                        }
                        break;
                    default:
                        break;
                }
                //新建一个bmp图片，并制定宽高
                System.Drawing.Image thumbnailImage = new Bitmap(towidth, toheight);
                //新建一个画板
                Graphics newpic = Graphics.FromImage(thumbnailImage);
                //设置高质量插值法
                newpic.InterpolationMode = InterpolationMode.High;
                //设置高质量,低速度呈现平滑程度
                newpic.SmoothingMode = SmoothingMode.HighQuality;
                //清空画布并以透明背景色填充
                newpic.Clear(Color.Transparent);
                //在指定位置并且按指定大小绘制原图片的指定部分
                newpic.DrawImage(oldimage, new Rectangle(0, 0, towidth, toheight),
                   new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);
                string S_FileName = "s_" + FileName;
                switch (file.PostedFile.FileName.Split(".".ToCharArray())[1].ToUpper())
                {
                    case "JPEG":
                    case "JPG":
                        thumbnailImage.Save(path + S_FileName, ImageFormat.Jpeg);
                        break;
                    case "GIF":
                        thumbnailImage.Save(path + S_FileName, ImageFormat.Jpeg);
                        break;
                    case "PNG":
                        thumbnailImage.Save(path + S_FileName, ImageFormat.Png);
                        break;
                    case "BMP":
                        thumbnailImage.Save(path + S_FileName, ImageFormat.Jpeg);
                        break;
                    default:
                        thumbnailImage.Save(path + S_FileName, ImageFormat.Jpeg);
                        break;
                }
                oldimage.Dispose();
                thumbnailImage.Dispose();
                newpic.Dispose();
                return S_FileName;//返回处理后的图片名称
            }
            else//如果图片已经存在则返回0，虽然概率几乎是0，但我感觉还是加上比较稳妥，^_^
            {
                return "0";
            }
        }

        /// <summary>
        /// 生成文件名（包括路径）
        /// </summary>
        /// <param name="file">上传控件</param>
        /// <param name="filesrc">上传到的目录</param>
        /// <returns>根据当前时间并加入随机数</returns>
        public static string filename(FileUpload file)
        {
            //得到当前时间精确到毫秒
            string FileName = DateTime.Now.ToString("yyMMddHHmmss") + DateTime.Now.Millisecond.ToString();
            //得到随机数
            char[] s = new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G'
          ,'J','K','L','M','N','P','Q','R','S','T','U','V','W'
          ,'X','Y','Z'};
            string num = "";
            Random r = new Random();
            for (int i = 0; i < 6; i++)
            {
                num += s[r.Next(0, s.Length - 1)].ToString();
            }
            //得到文件扩展名
            string FileEx = file.PostedFile.FileName.Split(".".ToCharArray())[1].ToUpper();
            //得到文件名并返回
            return FileName + num + "." + FileEx;
        }

        /// <summary>
        /// 将图像流保存
        /// </summary>
        /// <param name="ss">源图像流</param>
        /// <param name="savepath">保存路径</param>
        /// <param name="ContentType">文件保存类型（jpg,gif,bmp,png）</param>
        public static void SaveStream(Stream ss, string savepath, string ContentType)
        {
            try
            {
                Bitmap img = new Bitmap(ss);
                Bitmap newimg = new Bitmap(img.Width, img.Height);
                //新建画板
                Graphics gg = Graphics.FromImage(newimg);
                //设置高质量插值法
                gg.InterpolationMode = InterpolationMode.High;
                //设置高质量，低速度呈现平滑程度
                gg.SmoothingMode = SmoothingMode.HighSpeed;
                //清空画布并以透明色填充
                gg.Clear(Color.Transparent);
                //绘制图片
                gg.DrawImage(img, 0, 0);
                switch (ContentType.ToLower())
                {
                    case "bmp":
                        newimg.Save(savepath, ImageFormat.Bmp);
                        break;
                    case "gif":
                        newimg.Save(savepath, ImageFormat.Gif);
                        break;
                    case "jpg":
                        newimg.Save(savepath, ImageFormat.Jpeg);
                        break;
                    case "png":
                        newimg.Save(savepath, ImageFormat.Png);
                        break;
                }
                img.Dispose();
                newimg.Dispose();
                gg.Dispose();
            }
            catch (Exception)
            {

            }
        }
    }
}
